package com.chukun.disruptor.netty.disruptor.producer;

import com.chukun.disruptor.netty.bean.TranslatorData;
import com.chukun.disruptor.netty.disruptor.entity.TranslatorDataWrapper;
import com.lmax.disruptor.RingBuffer;
import io.netty.channel.ChannelHandlerContext;

public class MessageProducer {

    private String producerID;
    private RingBuffer<TranslatorDataWrapper> ringBuffer;

    public MessageProducer(String producerID,RingBuffer<TranslatorDataWrapper> ringBuffer){
        this.producerID = producerID;
        this.ringBuffer = ringBuffer;
    }

    public void onData(TranslatorData translatorData, ChannelHandlerContext ctx){
        //1 在生产者发送消息的时候, 首先 需要从我们的ringBuffer里面 获取一个可用的序号
        long sequence = ringBuffer.next();
        try {
            //2 根据这个序号, 找到具体的 "TranslatorDataWrapper" 元素 注意:此时获取的OrderEvent对象是一个没有被赋值的"空对象"
            TranslatorDataWrapper event = ringBuffer.get(sequence);
            //3 进行实际的赋值处理
            event.setData(translatorData);
            event.setCtx(ctx);
        }finally {
            //4 提交发布操作
            ringBuffer.publish(sequence);
        }
    }


}
